from django.shortcuts import render, redirect
from django.urls import reverse
from django.db.models import Q
from django import forms
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.contrib.auth import logout
from accounts.models import UserAccount
from accounts.utils.form import UserSearchForm
from accounts.utils.pagination import Pagination
from social.models import (
    Friend,
    Like,
    UserInform,
    PersonalityTag,
    Message,
    Post
)
from social.forms import UserProfileForm


def home(request, username):
    user_profile = UserInform.objects.get(user__username=username)
    user_info = request.session.get('info', {})
    user_id = user_info.get('id')
    if user_id:
        try:
            user_account = UserAccount.objects.get(id=user_id)
            username = user_account.username
        except UserAccount.DoesNotExist:
            pass
    content = {
        'user_profile': user_profile,
        'user_id': user_id,
        'username': username
    }
    return render(request, 'social_index.html', content)


def logout_user(request):

    logout(request)
    return redirect('login')  # 重定向到登录页面，你需要根据你的实际情况修改这里的 URL


def love(request):
    return render(request, 'love.html')


class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserInform
        fields = ['nickname', 'bio', 'avatar', 'background_image']


def edit(request, username):
    user_info = request.session.get('info', {})
    user_id = user_info.get('id')
    if user_id:
        try:
            user_account = UserAccount.objects.get(id=user_id)
            username = user_account.username
        except UserAccount.DoesNotExist:
            pass
    user_profile = UserInform.objects.get(user__username=username)
    personality_tags = PersonalityTag.objects.all()

    if request.method == 'POST':
        form = UserProfileForm(
            request.POST, request.FILES, instance=user_profile)

        # 获取表单提交的性格标签
        selected_tags = request.POST.getlist('personality_tags')

        if form.is_valid():
            updated_user_profile = form.save()

            # 更新性格标签
            updated_user_profile.personality_tags.set(selected_tags)

            return redirect(f'/social/{username}/')
    else:
        form = UserProfileForm(instance=user_profile)
        # 将已选择的标签传递到模板
        selected_tags_ids = user_profile.personality_tags.values_list(
            'id', flat=True)
    content = {
        'form': form,
        'personality_tags': personality_tags,
        'selected_tags_ids': selected_tags_ids,
        'user_id': user_id,
        'username': username
    }
    return render(request, 'edit.html', content)


def friend_management(request, username):
    user_info = request.session.get('info', {})
    user_id = user_info.get('id')
    if user_id:
        try:
            user_account = UserAccount.objects.get(id=user_id)
            username = user_account.username
        except UserAccount.DoesNotExist:
            pass
    current_user = UserInform.objects.get(user__username=username)

    # 获取用户的好友，包括好友的相关信息
    user_friends = Friend.objects.filter(
        user=current_user).select_related('friend__user')
    content = {
        'user_friends': user_friends,
        'username': username,
        'user_id': user_id
    }
    return render(request, 'friendmanage.html', content)


def delete_friend(request, friend_username, current_username):
    """删除好友"""
    current_user = UserInform.objects.get(
        user__username=current_username)
    friend_user = UserInform.objects.get(
        user__username=friend_username)

    # 删除好友
    Friend.objects.filter(user=current_user, friend=friend_user).delete()

    return redirect('manage_profile', username=current_username)


def friendadd(request, username):
    """添加好友"""
    current_user = UserInform.objects.get(user__username=username)
    user_info = request.session.get('info', {})
    user_id = user_info.get('id')

    # Find the current user's friends
    current_user_friends = Friend.objects.filter(
        user=current_user).values_list('friend__user', flat=True)

    # Initialize the form
    user_search_form = UserSearchForm(request.GET)

    # Search
    data_dict = {}
    if user_search_form.is_valid():
        search_data = user_search_form.cleaned_data.get('q', '')
        if search_data:
            # Using a foreign key field for searching
            data_dict['user__username__contains'] = search_data
    # Exclude current user and their friends from the queryset
    queryset = UserInform.objects.exclude(
        Q(user=current_user.user) | Q(user__in=current_user_friends)).filter(**data_dict)

    # Pagination
    page_object = Pagination(request, queryset)
    content = {
        'queryset': page_object.page_queryset,
        'page_string': page_object.html(),
        'user_search_form': user_search_form,
        'username': username,
        'user_id': user_id
    }
    return render(request, 'friendadd.html', content)


def send_friend_request(request, friend_username, current_username):
    """发送好友请求"""
    # 获取当前用户和被添加好友的用户
    current_user = UserInform.objects.get(
        user__username=current_username)
    friend_user = UserInform.objects.get(
        user__username=friend_username)

    print(f"Current User: {current_user}")
    print(f"Friend User: {friend_user}")

    # 检查是否已经是好友，如果不是，则添加好友
    if not Friend.objects.filter(user=current_user, friend=friend_user).exists():
        Friend.objects.create(user=current_user, friend=friend_user)

    return redirect(reverse('add_profile', args=[current_username]))


def like_user(request, user_name, friend_name):
    """点赞"""
    user = UserInform.objects.get(user__username=user_name)
    friend = UserInform.objects.get(user__username=friend_name)
    Like.objects.create(sender=user, receiver=friend)
    friend.total_likes += 1
    friend.save()
    return redirect('manage_profile', username=user_name)


def huizan(request, user_name, friend_name):
    """回赞"""
    user = UserInform.objects.get(user__username=user_name)
    friend = UserInform.objects.get(user__username=friend_name)
    Like.objects.create(sender=user, receiver=friend)
    friend.total_likes += 1
    friend.save()
    return redirect('view_likes', username=user_name)


def view_likes(request, username):
    """查看点赞情况"""
    # 获取用户信息
    user_profile = UserInform.objects.get(user__username=username)
    user_info = request.session.get('info', {})
    user_id = user_info.get('id')
    if user_id:
        try:
            user_account = UserAccount.objects.get(id=user_id)
            username = user_account.username
        except UserAccount.DoesNotExist:
            pass
    # 获取用户收到的所有点赞
    likes_received = Like.objects.filter(receiver=user_profile)

    # 设置每页显示的点赞数量
    items_per_page = 10
    paginator = Paginator(likes_received, items_per_page)

    # 获取当前页码
    page = request.GET.get('page')

    try:
        # 获取当前页的点赞列表
        likes_page = paginator.page(page)
    except PageNotAnInteger:
        # 如果页码不是一个整数，显示第一页
        likes_page = paginator.page(1)
    except EmptyPage:
        # 如果页码超出范围，显示最后一页
        likes_page = paginator.page(paginator.num_pages)

    content = {
        'user_profile': user_profile,
        'likes_page': likes_page,
        'user_id': user_id,
        'username': username
    }

    return render(request, 'love.html', content)


def friend_messages(request, username):
    """查看留言"""
    current_user = UserInform.objects.get(user__username=username)
    user_messages = Message.objects.filter(receiver=current_user)
    user_info = request.session.get('info', {})
    user_id = user_info.get('id')

    content = {
        'user_messages': user_messages,
        'username': username,
        'user_id': user_id
    }
    return render(request, 'friend_message.html', content)


def leave_message(request, sender_username, receiver_username):
    """留言"""
    user_info = request.session.get('info', {})
    user_id = user_info.get('id')
    if user_id:
        try:
            user_account = UserAccount.objects.get(id=user_id)
            username = user_account.username
        except UserAccount.DoesNotExist:
            pass
    if request.method == 'POST':
        sender_user = UserInform.objects.get(
            user__username=sender_username)
        receiver_user = UserInform.objects.get(
            user__username=receiver_username)
        content = request.POST.get('message_content', '')

        # 创建留言
        Message.objects.create(
            sender=sender_user, receiver=receiver_user, content=content)

        return redirect('manage_profile', username=sender_username)

    # 处理 GET 请求，渲染留言表单
    content = {
        'sender_username': sender_username,
        'receiver_username': receiver_username,
        'user_id': user_id,
        'username': username
    }
    return render(request, 'leave_message.html', content)


def huifu(request, sender_username, receiver_username):
    """回复留言"""
    user_info = request.session.get('info', {})
    user_id = user_info.get('id')
    if user_id:
        try:
            user_account = UserAccount.objects.get(id=user_id)
            username = user_account.username
        except UserAccount.DoesNotExist:
            pass
    if request.method == 'POST':
        sender_user = UserInform.objects.get(
            user__username=sender_username)
        receiver_user = UserInform.objects.get(
            user__username=receiver_username)
        content = request.POST.get('message_content', '')

        # 创建留言
        Message.objects.create(
            sender=sender_user, receiver=receiver_user, content=content)

        return redirect('friend_messages', username=sender_username)

    # 处理 GET 请求，渲染留言表单
    content = {
        'sender_username': sender_username,
        'receiver_username': receiver_username,
        'user_id': user_id,
        'username': username
    }
    return render(request, 'huifu_message.html', content)


class PostForm(forms.Form):
    content = forms.CharField(widget=forms.Textarea)
    image = forms.ImageField(required=False)


def create_post(request, username):
    """发朋友圈"""
    user_info = request.session.get('info', {})
    user_id = user_info.get('id')
    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            user = UserInform.objects.get(user__username=username)
            content = form.cleaned_data['content']
            image = form.cleaned_data['image']
            Post.objects.create(
                user=user, content=content, image=image)
            return redirect('view_posts', username=username)
    else:
        form = PostForm()

    content = {
        'form': form,
        'username': username,
        'user_id': user_id
    }

    return render(request, 'create_post.html', content)


def view_posts(request, username):
    user_info = request.session.get('info', {})
    user_id = user_info.get('id')
    user = UserInform.objects.get(user__username=username)
    friends = Friend.objects.filter(user=user)
    friend_posts = Post.objects.filter(
        user__in=friends.values('friend'))

    content = {
        'user': user,
        'friend_posts': friend_posts,
        'username': username,
        'user_id': user_id
    }

    return render(request, 'view_posts.html', content)


def my_posts(request, username):
    user_info = request.session.get('info', {})
    user_id = user_info.get('id')

    user = UserInform.objects.get(user__username=username)
    user_posts = Post.objects.filter(user=user)

    if request.method == 'POST':
        post_id = request.POST.get('post_id')
        post_to_delete = Post.objects.get(id=post_id)
        post_to_delete.delete()
        return redirect('my_posts', username=username)

    content = {
        'user': user,
        'user_posts': user_posts,
        'user_id': user_id,
        'username': username
    }

    return render(request, 'my_posts.html', content)
